package com.hcycom.hcyclient.controller;

import com.hcycom.hcymodel.pojo.RuleTest;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 负载均衡测试类：
 * 默认是服务器的均衡使用
 */
@RestController
@RequestMapping(value ="/test",produces = "application/json")
public class RestTemplateController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/test")
    public List<RuleTest> test(@RequestBody RuleTest ruleTest){
        List<RuleTest> list=this.restTemplate.postForObject("http://ruleServer/test/select",ruleTest,List.class);
        return list;
    }
    /******************************断路器实例*********************************/
    @RequestMapping(value = "/getById")
   @HystrixCommand(fallbackMethod = "defalutRuleTest",commandProperties = {
           @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")             //使用隔离策略使得请求和回调使用的是同一个线程
   })
    public List<RuleTest> getById(@RequestBody RuleTest ruleTest){
        List<RuleTest> list=this.restTemplate.postForObject("http://ruleServer/test/select",ruleTest,List.class);
        return list;
    }

    /**
     * 请求失败的回调函数
     * @param ruleTest
     * @return
     */
    public List<RuleTest> defalutRuleTest(@RequestBody RuleTest ruleTest){
        List<RuleTest> list=new ArrayList<RuleTest>();
        RuleTest rule=new RuleTest();
        rule.setName("陌生人");
        list.add(rule);
        return list;
    }
}
